package server;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.sql.Date;

public class MulticastServerThread extends Thread {
	private long ONE_SECOND = 1000;
	private DatagramSocket socket;
	volatile boolean running;

    public MulticastServerThread() throws IOException {
        this("MulticastServerThread");
    }
    
    public MulticastServerThread(String name) throws IOException {
	    super(name);
	    socket = new DatagramSocket(4445);
	} 
    
    public void shutdown() {
    	running = false;
    }

    public void run() {
    	running = true;
        while (running) {
            try {
                byte[] buf = new byte[256];

                // construct quote
                String dString = null;
                dString = new Date(System.currentTimeMillis()).toString();
                buf = dString.getBytes();

                // send it
                InetAddress group = InetAddress.getByName("230.0.0.1");
                DatagramPacket packet = new DatagramPacket(buf, buf.length, group, 4446);
                socket.send(packet);

                // sleep for a while
				try {
				    sleep(ONE_SECOND);
				} catch (InterruptedException e) { }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
	socket.close();
    }
}
